Skip to content

Conversation

@clarfonthey
Copy link
Contributor

The primary addition here is OccupiedEntry::replace_key, which allows replacing the key in the map. Since this is an uncommon operation, I decided to make it unsafe and not check for the equivalence of the key, but that can potentially be changed.

The other change that is made here is VacantEntryRef::{insert_with_key,insert_entry_with_key} now have unchecked versions which do not check the equivalence of the key, to ensure the same behaviour with the replace function never panicking.

Unfortunately, an UnsafeCell is required to truly make this API work without accessing internals, but it shouldn't ultimately matter, I think. The result is the find_or_find_insert_index method of HashMap is no longer exported, and instead the entry API is used by HashSet. Now, the only remaining raw table API for HashSet is RawExtractIf, to be fixed later.

Comment on lines +3800 to +3847
/// assert!(std::ptr::eq(replaced, old_key));
/// assert!(std::ptr::eq(*entry.key(), new_key));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seemed like the best way to ensure the key was truly "replaced" instead of having a custom struct with a custom PartialEq implementation.

@clarfonthey clarfonthey force-pushed the replace-key branch 2 times, most recently from c232221 to 8db923f Compare January 27, 2026 19:31
src/map.rs Outdated
/// # }
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub unsafe fn replace_key(&mut self, key: K) -> K {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is an unsafe function, I would prefer if this was called replace_key_unchecked. This explicitly calls out that key equality is not checked and that you are responsible for ensuring this.

This also leaves the door open for a safe replace_key method which has this check.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In that case, I'll just add that method and have both cases from the start.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants